<script>
import FieldPanel from './FieldPanel'
import {getCurrentInstance, provide, ref} from 'vue'
import UserComponents from './allitem'
import CUserComponents from './container/callitem'
import PropertyPanel from './PropertyPanel'
import {postRequest} from '../../api/star_horse'
import {confirm, error, warning} from '../../utils/message'

export default {
  name: 'DynamicForm',
  setup() {
    let dragingItem = ref({})
    let list = ref([])
    let isPreview = ref(false)
    let isEdit = ref(true)
    let activeTab = ref('first')
    let activeId = ref('')
    let starHorseDynamicForm = ref({})
    let editable = ref(true)
    const {proxy} = getCurrentInstance();
    provide('starHorseDynamicForm', starHorseDynamicForm)
    provide('dragingItem', dragingItem)
    provide('tableEditable', editable)
    let formInfo = ref({
      rules: '',
      inline: false,
      labelPosition: 'left',
      labelWidth: '',
      labelSuffix: '',
      hideRequiredAsterisk: false,
      requireAsteriskPosition: 'left',
      showMessage: true,
      inlineMessage: false,
      statusIcon: false,
      validateOnRuleChange: true,
      size: 'default',
      disabled: false,
      scrollToError: false
    })
    provide('formInfo', formInfo)
    let formDatas = ref({
      formInfo: formInfo,
      dataList: list,
      activeId: activeId,
      isEdit: isEdit
    })

    const activeItemFun = function (name, data, item) {
      let funcs = proxy.$options.methods;
      let fun = funcs[name];
      fun.call(proxy, data, item);
    };
    provide("activeItemFun", activeItemFun);
    // let activeDatas = ref({
    //   fieldList: {}, formProps: {}, advancedFieldList: {}, actions: {}
    // })
    provide("activeItemData", formDatas);
    return {
      list,
      formDatas,
      isPreview,
      formInfo,
      starHorseDynamicForm,
      isEdit,
      activeTab,
      dragingItem,
      editable
    }
  },

  components: {
    PropertyPanel,
    FieldPanel,
    ...UserComponents,
    ...CUserComponents
  },
  methods: {
    closeAction() {
      this.isEdit = !this.isEdit
    },
    clearData() {
      let _this = this
      _this.list = []
      _this.formDatas = {
        dataList: _this.list,
        formInfo: _this.formInfo,
        isEdit: _this.isEdit,
        activeId: ''
      }
    },
    preview() {
      this.isPreview = !this.isPreview
      this.isEdit = !this.isEdit
    },
    save() {
      let _this = this
      let dynameForm = _this.formDatas.formInfo
      if (!dynameForm.formName) {
        warning('请先填写表单')
        _this.activeTab = 'second'
        _this.$refs.propertyRef.$refs.formRef.$refs.itemFormInfo.validate(
            (evt) => {
            }
        )
        return
      }
      dynameForm['dataList'] = JSON.stringify(_this.formDatas.dataList)
      postRequest('system-config/system/dynamicForm/merge', dynameForm).then((res) => {
        //添加成功后是否还要继续添加，
        confirm(
            res.data.cnMessage + ',是否继续留在当前页面',
            function (data) {
              if (!data) {
                let sdata = {
                  path: '/dynamicform',
                  componentName: 'DynamicForm'
                }
                _this.$store.dispatch(
                    'clearCache',
                    sdata.componentName
                )
                _this.$store.dispatch('clearNavBar', sdata)
              }
            }
        )
      }).catch((err) => {
        error('操作异常:' + err)
      })
    },
    createData() {
    },
    formInfoChange(data) {
    },
    selectItem(data, parentCompType) {
      let _this = this
      _this.formDatas.activeId = data.id
      //当前组件是否在容器组件内
      _this.formDatas.parentCompType = parentCompType
      _this.formDatas.compType = data.compType
    },
    getComponentName(data) {
      return data.type + '-item'
    },
    onDragAdd(evt, dataList) {
      let _this = this
      for (let i in dataList) {
        let temp = dataList[i]
        if (temp.id === _this.dragingItem.id) {
          _this.formDatas.activeId = temp.id
          _this.formDatas.compType = temp.compType
          _this.formDatas.dataList = _this.list
          _this.formDatas.parentCompType = ''
        }
      }
    }
  }
}
</script>

<style lang = "scss" scoped>
/deep/ .el-card__body {
  padding: 5px 20px;
  height: inherit;
}

/deep/ .el-divider--horizontal {
  margin: 10px 0px;
}

.form_content {
  display: flex;
  width: 100%;
  height: calc(100vh - 142px);
  box-sizing: border-box;
  flex-direction: column;

  .dynamic-toolbar {
    height: 30px;
    width: 100%;
    vertical-align: middle;
    justify-content: right;
    align-items: center;
    display: flex;
    right: 15px;
  }

  .form-main {
    display: flex;
    flex-direction: row;
    height: calc(100vh - 200px);
    padding: 5px 0px;
    box-sizing: border-box;

    .side-panel {
      width: 270px !important;
      justify-content: flex-start;
      background: #ffffff;
    }

    .main-design-outer {
      height: inherit;
      flex: 1;
      background: #f1f2f3;
      border-radius: 3px;
      padding: 0px 8px;
      position: relative;
      justify-content: center;

      .main-design {
        width: inherit;
        height: inherit;
        background: rgba(255, 255, 255, 0.8);
        overflow: auto;
      }
    }

    .side-panel-item {
      width: 250px;
      margin-right: 10px;
    }
  }
}
</style>
<template>
  <star-horse-dialog
      :visible = "isPreview"
      @closeAction = "closeAction"
      :title = "'样式预览'"
      :is-view = "true"
  >
    <template v-for = "data in list">
      <component
          :field = "data"
          :form-datas = "formDatas"
          :is = "data.type+'-container'"
          :star-horse-dynamic-form = "starHorseDynamicForm"
          @selectItem = "selectItem"
          v-if = "data.compType==='container'"
      >
      </component>
      <component
          :field = "data"
          :form-datas = "formDatas"
          :is = "getComponentName(data)"
          :star-horse-dynamic-form = "starHorseDynamicForm"
          @selectItem = "selectItem"
          v-else-if = "data.compType==='formItem'"
      />
    </template>
  </star-horse-dialog>

  <el-card class = "form_content">
    <div class = "dynamic-toolbar">
      <el-button
          :disabled = "list.length==0"
          @click = "clearData"
          title = "清空"
          type = "small"
      >
        <user-icon icon = "fa fa-trash"/>&nbsp;清空
      </el-button>
      <el-button
          :disabled = "list.length==0"
          @click = "preview"
          title = "预览"
          type = "small"
      >
        <user-icon icon = "fa fa-search"/>&nbsp;预览
      </el-button>
      <el-button
          :disabled = "list.length==0"
          @click = "save"
          title = "保存"
          type = "small"
      >
        <user-icon icon = "fa fa-save"/>&nbsp;保存
      </el-button>
      <el-button
          :disabled = "list.length==0"
          @click = "createCode"
          title = "生成代码"
          type = "small"
      >
        <user-icon icon = "fa fa-file-text"/>&nbsp;生成代码
      </el-button>
    </div>
    <el-divider/>
    <div class = "form-main">
      <div class = "side-panel">
        <field-panel/>
      </div>

      <div class = "main-design-outer">
        <el-form
            style = "height: inherit"
            :disabled = "formInfo['disabled']"
            :hide-required-asterisk = "formInfo['hideRequiredAsterisk']"
            :inline = "formInfo.inline"
            :inline-message = "formInfo['inlineMessage']"
            :label-position = "formInfo['labelPosition']"
            :label-suffix = "formInfo['labelSuffix']"
            :label-width = "formInfo['labelWidth']"
            :model = "starHorseDynamicForm"
            :require-asterisk-position = "formInfo['requireAsteriskPosition']"
            :rules = "formInfo.rules"
            :scroll-to-error = "formInfo['scrollToError']"
            :show-message = "formInfo['showMessage']"
            :size = "formInfo['size']"
            :status-icon = "formInfo['statusIcon']"
            :validate-on-rule-change = "formInfo['validateOnRuleChange']">
          <draggable
              @add = "(evt)=>onDragAdd(evt,list)"
              class = "main-design"
              :animation = "100"
              group = "starHorseGroup"
              :disable = "!editable"
              ghostClass = "ghost"
              :list = "list"
          >
            <template v-for = "(data,index) in list">
              <component
                  :key = "index"
                  :field = "data"
                  :form-datas = "formDatas"
                  :is = "data.type+'-container'"
                  :star-horse-dynamic-form = "starHorseDynamicForm"
                  @selectItem = "selectItem"
                  v-if = "data.compType==='container'"
              />
              <component
                  :key = "index+100"
                  :field = "data"
                  :form-datas = "formDatas"
                  :is = "getComponentName(data)"
                  :parent-comp-type = "'item'"
                  :star-horse-dynamic-form = "starHorseDynamicForm"
                  @selectItem = "selectItem"
                  v-else-if = "data.compType=='formItem'"
              />
            </template>
          </draggable>
        </el-form>
      </div>
      <div class = "side-panel-item">
        <property-panel
            :active-tab = "activeTab"
            :form-datas = "formDatas"
            @formInfoChange = "formInfoChange"
            ref = "propertyRef"
        />
      </div>

    </div>
  </el-card>
</template>
